<template>
  <el-container>
    <el-header>
      <h1>SSM-CRUD</h1>
    </el-header>
    <el-main>
      <el-row type="flex" class="row-bg" justify="end">
        <el-col :span="3">
          <div class="grid-content bg-purple-dark">
            <el-button type="primary" @click="addEmp()">新增</el-button>
            <el-button type="danger" @click="deleteSelectedEmps()"
              >删除</el-button
            >
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24"
          ><div class="grid-content bg-purple-dark">
            <el-table
              :data="pageInfo.list"
              style="width: 100%"
              v-loading="loading"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"> </el-table-column>
              <el-table-column label="empId" prop="empId"> </el-table-column>
              <el-table-column label="empName" prop="empName">
              </el-table-column>
              <el-table-column
                label="gender"
                prop="gender"
                :formatter="formatSex"
              >
              </el-table-column>
              <el-table-column label="email" prop="email"> </el-table-column>
              <el-table-column label="deptId" prop="department.deptId">
              </el-table-column>
              <el-table-column label="deptName" prop="department.deptName">
              </el-table-column>
              <el-table-column align="right">
                <template slot="header" slot-scope="">
                  <el-input
                    v-model="search"
                    size="mini"
                    placeholder="输入关键字搜索"
                  />
                </template>
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    @click="handleEdit(scope.$index, scope.row)"
                    >Edit</el-button
                  >
                  <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                    >Delete</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </div></el-col
        >
      </el-row>
      <!-- 添加员工模态框 -->
      <el-dialog
        title="添加员工"
        :visible.sync="dialogFormVisible_addEmp"
        :show-close="false"
      >
        <el-form :model="form" :rules="rules" ref="addForm">
          <el-form-item
            label="empName:"
            :label-width="formLabelWidth"
            prop="empName"
          >
            <el-input
              v-model="form.empName"
              autocomplete="off"
              placeholder="empName"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="gender:"
            :label-width="formLabelWidth"
            class="form_item_left"
            prop="gender"
          >
            <el-radio v-model="form.gender" label="M">男</el-radio>
            <el-radio v-model="form.gender" label="F">女</el-radio>
          </el-form-item>
          <el-form-item
            label="email:"
            :label-width="formLabelWidth"
            prop="email"
          >
            <el-input
              v-model="form.email"
              autocomplete="off"
              placeholder="email@163.com"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="部门:"
            :label-width="formLabelWidth"
            class="form_item_left"
            prop="dId"
          >
            <el-select v-model="form.dId" placeholder="请输入">
              <el-option
                v-for="item in depts"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            @click="(dialogFormVisible_addEmp = false), resetForm('addForm')"
            >取 消</el-button
          >
          <el-button type="primary" @click="submitForm('addForm')"
            >确 定</el-button
          >
        </div>
      </el-dialog>
      <!-- 修改员工模态框 -->
      <el-dialog
        title="修改员工信息"
        :visible.sync="dialogFormVisible_editEmp"
        :show-close="false"
      >
        <el-form :model="editForm" :rules="rules" ref="editForm">
          <el-form-item
            label="empName:"
            :label-width="formLabelWidth"
            class="form_item_left"
          >
            <span>{{ editForm.empName }}</span>
          </el-form-item>
          <el-form-item
            label="gender:"
            :label-width="formLabelWidth"
            class="form_item_left"
            prop="gender"
          >
            <el-radio v-model="editForm.gender" label="M">男</el-radio>
            <el-radio v-model="editForm.gender" label="F">女</el-radio>
          </el-form-item>
          <el-form-item
            label="email:"
            :label-width="formLabelWidth"
            prop="email"
          >
            <el-input
              v-model="editForm.email"
              autocomplete="off"
              placeholder="email@163.com"
            ></el-input>
          </el-form-item>
          <el-form-item
            label="部门:"
            :label-width="formLabelWidth"
            class="form_item_left"
            prop="dId"
          >
            <el-select v-model="editForm.dId" placeholder="请输入">
              <el-option
                v-for="item in depts"
                :key="item.deptId"
                :label="item.deptName"
                :value="item.deptId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button
            @click="(dialogFormVisible_editEmp = false), resetForm('editForm')"
            >取 消</el-button
          >
          <el-button type="primary" @click="submitForm('editForm')"
            >更 新</el-button
          >
        </div>
      </el-dialog>
    </el-main>
    <el-footer
      ><el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageInfo.pageNum"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pageInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pageInfo.total"
      >
      </el-pagination
    ></el-footer>
  </el-container>
</template>

<script>
import {
  getAllEmps,
  getAllDepts,
  saveEpm,
  checkNameSame,
  updateEpm,
  deleteEmpById,
  deleteEmps,
} from "@/api/index";
export default {
  name: "EmployeesList",
  props: {},
  data() {
    var checkEmpName = (rule, value, callback) => {
      const NameRegex = /(^[a-zA-Z0-9_-]{6,16}$)|(^[\u4e00-\u9fa5]{2,5})/;
      if (value == "" || value == undefined || value == null) {
        return callback(new Error("用户名不能为空"));
      } else if (!NameRegex.test(value)) {
        return callback(
          new Error("用户名请使用a-z A-Z 0-9 _ - 组合，且长度必须为6-16")
        );
      }
      checkNameSame(value).then(
        (res) => {
          if (res.data.code == 100) {
            callback();
          } else {
            callback(new Error(res.data.extend.va_msg));
          }
        },
        (res) => {
          this.$message.error("网络请求失败");
        }
      );
    };
    var checkEmail = (rule, value, callback) => {
      const EmailRegex =
        /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,6})$/;
      if (value == "" || value == undefined || value == null) {
        return callback(new Error("邮箱不能为空"));
      } else if (!EmailRegex.test(value)) {
        return callback(new Error("请输入正确的邮箱"));
      } else {
        callback();
      }
    };
    return {
      pageInfo: {},
      search: "",
      dialogFormVisible_addEmp: false,
      dialogFormVisible_editEmp: false,
      loading: true,
      multipleSelection: [],
      form: {
        empName: "",
        gender: "M",
        email: "",
        dId: 1,
      },
      editForm: {},
      formLabelWidth: "120px",
      depts: [],
      rules: {
        empName: [{ validator: checkEmpName, trigger: "blur" }],
        email: [{ validator: checkEmail, trigger: "blur" }],
      },
    };
  },
  created() {
    this.getEmpsList();
  },
  methods: {
    getEmpsList(pn, pageSize) {
      this.loading = true;
      getAllEmps(pn, pageSize).then((res) => {
        this.pageInfo = res.data.extend.pageInfo;
        this.loading = false;
      });
    },
    handleEdit(index, row) {
      getAllDepts()
        .then((res) => {
          this.depts = res.data.extend.depts;
        })
        .catch((res) => {
          this.$message.error("获取部门列表失败");
        });
      this.editForm = { ...row }; //实现浅拷贝
      this.dialogFormVisible_editEmp = true;
    },
    handleDelete(index, row) {
      this.$confirm(
        "此操作将永久删除员工" + row.empName + "的信息, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          deleteEmpById(row).then(
            (res) => {
              if (res.data.code == 100) {
                this.$message({
                  type: "success",
                  message: "删除成功!",
                });
                this.getEmpsList(this.pageInfo.pageNum, this.pageInfo.pageSize);
              } else {
                this.$message.error("删除员工失败！");
                console.log(res.data.extend.errorFields);
              }
            },
            (res) => {
              this.$message.error("网络请求失败");
            }
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    handleSizeChange(pageSize) {
      this.getEmpsList(this.pageInfo.pageNum, pageSize);
    },
    handleCurrentChange(pn) {
      this.getEmpsList(pn, this.pageInfo.pageSize);
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    deleteSelectedEmps() {
      if (this.multipleSelection.length != 0) {
        this.$confirm("此操作将永久删除员工信息, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            deleteEmps(this.multipleSelection).then(
              (res) => {
                if (res.data.code == 100) {
                  this.$message({
                    type: "success",
                    message: "删除成功!",
                  });
                  this.getEmpsList(
                    this.pageInfo.pageNum,
                    this.pageInfo.pageSize
                  );
                } else {
                  this.$message.error("删除员工失败！");
                  console.log(res.data.extend.errorFields);
                }
              },
              (res) => {
                this.$message.error("网络请求失败");
              }
            );
          })
          .catch(() => {
            this.$message({
              type: "info",
              message: "已取消删除",
            });
          });
      } else {
        this.$message({
          type: "error",
          message: "请选择操作的内容",
        });
      }
    },
    formatSex(row, column, cellValue) {
      undefined;
      if (cellValue === "M") {
        return "男";
      } else {
        return "女";
      }
    },
    addEmp() {
      this.dialogFormVisible_addEmp = true;
      getAllDepts()
        .then((res) => {
          this.depts = res.data.extend.depts;
        })
        .catch((res) => {
          this.$message.error("获取部门列表失败");
        });
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          switch (formName) {
            case "addForm":
              saveEpm(this.form).then(
                (res) => {
                  if (res.data.code == 100) {
                    this.dialogFormVisible_addEmp = false;
                    this.$message({
                      message: "添加成功!",
                      type: "success",
                    });
                    this.getEmpsList(
                      this.pageInfo.total,
                      this.pageInfo.pageSize
                    );
                    this.resetForm("addForm");
                  } else {
                    this.$message.error("添加员工失败！");
                    console.log(res.data.extend.errorFields);
                  }
                },
                (res) => {
                  this.$message.error("网络请求失败");
                }
              );
              break;
            case "editForm":
              updateEpm(this.editForm).then(
                (res) => {
                  if (res.data.code == 100) {
                    this.dialogFormVisible_editEmp = false;
                    this.$message({
                      message: "修改成功!",
                      type: "success",
                    });
                    this.getEmpsList(
                      this.pageInfo.pageNum,
                      this.pageInfo.pageSize
                    );
                  } else {
                    this.$message.error("修改员工失败！");
                  }
                },
                (res) => {
                  this.$message.error("网络请求失败");
                }
              );
              break;
          }
        } else {
          this.$message.error("请输入正确的员工信息！");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
.form_item_left {
  text-align: left;
}
</style>
